<template>
  <div class="app-container">
    <el-form :model="forms" ref="managementRef" :inline="true" :rules="rules" label-width="68px">
      <el-form-item label="挂号编号" prop="registrationId">
        <el-input
            v-model="forms.registrationId"
            placeholder="请输入挂号管理id"
            readonly
        />
      </el-form-item>
      <el-form-item label="科室名" prop="departmentName">
        <select v-model="forms.departmentId" placeholder="请选择科室" style="height: 30px;width: 175px;border-color: #E7E7E7">
          <option value="" disabled selected>请选择科室</option>
          <option v-for="option in Depattmentlist" :key="option.departmentName" :value="option.departmentId">
            {{ option.departmentName }}
          </option>
        </select>
      </el-form-item>

      <el-form-item label="科室医生" prop="name">
        <el-input
            :disabled="forms.departmentId == null"
            v-model="forms.employee1.name"
            placeholder="请输入员工名"
            @click="getdoctorlist(forms.departmentId,forms.registrationDate)"
        />
        <div v-if="opendoctorlist" class="dropdown">
          <div
              v-for="(item, index) in doctorlist"
              :key="index"
              @click="selectDoctor(item)"
              class="dropdown-item"
          >
            <div :class="['option-block', { 'selected': selectValue === item.id }]">
              <span class="option-title" >{{ item.name }}</span>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="诊断类型" prop="diagnosisType">
        <select placeholder="请选择诊断类型" v-model="forms.diagnosisType" style="height: 30px;width: 175px;border-color: #E7E7E7">
          <option value="" disabled selected>请选择诊断类型</option>
          <option v-for="option in options" :key="option.value" :value="option.value">
            {{ option.label }}
          </option>
        </select>
      </el-form-item>


      <el-form-item label="挂号时间" prop="registrationTime">
        <el-date-picker clearable
                        v-model="forms.registrationDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择挂号时间"
                        :disabled="true">
        </el-date-picker>
      </el-form-item>


      <el-form-item label="挂号费用" prop="amount">

        <select placeholder="请选择费用类型" v-model="forms.registrationFeeId" style="height: 30px;width: 175px;border-color: #E7E7E7">
          <option value="" disabled selected>请选择挂号费</option>
          <option v-for="option in feelist" :key="option.registrationName+':'+option.amount" :value="option.id">
            {{ option.registrationName }} : {{ option.amount }}
          </option>
        </select>

      </el-form-item>
      <el-form-item label="挂号员" prop="name">
        <el-input
            v-model="forms.employee2.id"
            placeholder="请输入挂号员"
        />
      </el-form-item>
      <el-form-item label="剩余挂号" >
        <span>{{restregistration}}</span>
      </el-form-item>

    </el-form>

    <el-form-item>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">新增</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </el-form-item>

    <!-- 患者信息 -->
    <el-form :model="forms.value" ref="patientRef" :inline="true" :rules="rules" label-width="68px">
      <el-form-item label="患者姓名" prop="registrationId">
        <el-input  class="selected-item" @click="toggleDropdown"
            v-model="forms.patient"
            placeholder="请输入患者名"
        />
        <div v-if="isDropdownVisible" class="dropdown">
          <div
              v-for="(item, index) in userList"
              :key="index"
              @click="selectOption(item)"
              class="dropdown-item"
          >
            <div :class="['option-block', { 'selected': selectedValue === item.patientId }]">
              <span class="option-title" >{{ item.realName }}</span>
              <span class="option-description">{{ item.age }} 岁 - {{ item.phoneNumber }} - {{ item.gender }}</span>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="患者卡号" prop="membershipCardNumber">
        <el-input
            v-model="forms.membershipCardNumber"
            placeholder="请输入患者卡号"
        />

      </el-form-item>
      <el-form-item label="患者年龄" prop="age">
        <el-input
            v-model="forms.age"
            placeholder="请输入患者年龄"
        />
      </el-form-item>

<!--      <el-form-item label="出生日期" prop="registrationTime">-->
<!--        <el-date-picker clearable-->
<!--                        v-model="forms.registrationTime"-->
<!--                        type="date"-->
<!--                        value-format="YYYY-MM-DD"-->
<!--                        placeholder="请选择出生日期">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->

      <el-form-item label="性别" prop="amount">
        <el-input
            v-model="forms.gender"
            placeholder="请输入性别"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
            v-model="forms.phoneNumber"
            placeholder="请输入手机号"
        />
      </el-form-item>

      <el-form-item label="证件号码" prop="idCardNumber">
        <el-input
            v-model="forms.idCardNumber"
            placeholder="请输入证件号码"
        />
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input
            v-model="forms.address"
            placeholder="请输入地址"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="Management">
import {
  addManagemented,
  delManagement,
  getDepartment,
  getdoctor,
  getFee,
  getManagement,
  getrestcount,
  listManagement, reduceMount,
  updateManagement
} from "@/api/registration/addregistration/management";
import {Select} from "@element-plus/icons-vue";
import {onMounted, ref} from 'vue';
import {useRoute} from 'vue-router';
import {ElMessage} from 'element-plus'
import {addManagement} from "@/api/sn/management.js";

const { proxy } = getCurrentInstance();

const route = useRoute();  // 获取路由实例

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeRegistrationDate = ref([]);

const isDropdownVisible = ref(false);
const selectValue = ref(null)
const selectedValue = ref(null);
const selectedLabel = ref(null);
const opendoctorlist = ref(false);
const restregistration = ref("?")

const diagnosisclass = ref('');
const options = [
  { label: '初诊', value: '初诊' },
  { label: '复诊', value: '复诊' }
];

const toggleDropdown = () => {
  isDropdownVisible.value = !isDropdownVisible.value;
}

const selectOption = (item) => {
  selectedValue.value = item.patientId;
  selectedLabel.value = item.realName;
  forms.value.patient = item.realName;
  forms.value.patientId = item.patientId;
  forms.value.age = item.age;
  forms.value.phoneNumber = item.phoneNumber;
  forms.value.gender = item.gender;
  forms.value.address = item.address;
  forms.value.idCardNumber = item.idCardNumber;
  forms.value.membershipCardNumber = item.membershipCardNumber;
  isDropdownVisible.value = false;
  console.log("forms")
  console.log(forms.value)
  console.log(item)
}
const forms = ref({
  registrationId: null,
  patient:null,
  patientId: null,
  departmentId: null,
  departments:null,
  diagnosisType:null,
  employee1: {
    id:null,
    name: null,
  },
  employee2:{
    id:null,
    name: null,
  },
  registrationFeeId:null,
  registrationTime: null,//选择挂号预约的时间段
  registrationDate: null,
  idCardNumber:null,
  membershipCardNumber:null,

})



const data = reactive({
  form: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    registrationId: null,
    patient:null,
    membershipCardNumber:null,
    departments: null,
    diagnosisType:null,
    employee1:null,
    employee2:null,
    registrationFee:null,
    registrationTime: null,
    registrationDate: null,
    registrationFeeName: null,

  },
  rules: {}
});

function resetdoctor(){
  doctorlist.value = null
}

// 医生的选择
const doctorlist = ref([])
function getdoctorlist(departmentId,date){
  opendoctorlist.value=true
  resetdoctor()
  getdoctor(departmentId,date).then(response => {
    console.log(response.data)
    if (response.data){
      doctorlist.value=response.data
    }else {
      resetdoctor()
    }

  })
}
function selectDoctor(item){
    selectValue.value = item.id;
    forms.value.employee1.id = item.id;
    forms.value.employee1.name = item.name;
    console.log(item.id)
    console.log(forms.value.registrationDate)
    checkrestcount(item.id,forms.value.registrationDate)
    opendoctorlist.value=false
}


const userdata = reactive({
  userlist : {
    patientId:null,
    realName:null,
    phoneNumber:null,
    age:null,
    gender:null,
    address:null,
    membershipCardNumber:null,
  },
})
const Depattmentlist = ref();

function getDepartmentdata() {
  getDepartment().then(response =>{
    Depattmentlist.value = response.data;
    console.log("Depattmentlist")
    console.log(Depattmentlist.value)
  })
}
getDepartmentdata();

const { queryParams, form , rules } = toRefs(data);
const {userlist} = toRefs(userdata);

/** 查询新增挂号列表 */
function getList() {
  loading.value = true;
  userList.value.params = {};
  if (null != daterangeRegistrationDate && '' !== daterangeRegistrationDate) {
    userList.value.params["beginRegistrationDate"] = daterangeRegistrationDate.value[0];
    userList.value.params["endRegistrationDate"] = daterangeRegistrationDate.value[1];
  }
  listManagement().then(response => {
    userList.value = response;
    loading.value = false;
    console.log("userList")
    console.log(userList.value)
    console.log(response);
  });
}

// 取消按钮
function cancel() {
  reset();
}

// 表单重置
function reset() {
  forms.value = {
    registrationId: null,
    patient:null,
    patientId: null,
    departmentId: null,
    departments:null,
    diagnosisType:null,
    employee1: {
      id:null,
      name: null,
    },
    employee2:{
      id:null,
      name: null,
    },
    registrationFeeId:null,
    registrationTime: null,
    registrationDate: null,
    idCardNumber:null,
    membershipCardNumber:null,

  };
  proxy.resetForm("managementRef");
}
reset();
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeRegistrationDate.value = [];
  reset();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.registrationId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加新增挂号";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _registrationId = row.registrationId || ids.value;
  getManagement(_registrationId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改新增挂号";
  });
}

const feelist = ref();
/** 获取挂号费列表 */
function getFeelist(){
  getFee().then(response => {
    feelist.value = response.rows;
    console.log("Fee")
    console.log(feelist.value)
    console.log(response)
  })
}
/** 提交按钮 */
function submitForm() {

  proxy.$refs["managementRef"].validate(valid => {
    // 构建要发送的数据对象
    const
      queryParams = ref( {
        registrationId : forms.value.registrationId,      // 确保 registrationId 正确
        patientId : forms.value.patientId,                  // 确保 patientId 正确
        doctorId : forms.value.employee1.id,
        departmentId : forms.value.departmentId,
        registrationTime: thetime.value,
        registrationDate: thedate,
        registrationPeriod: period.value,
        registrationFeeId : forms.value.registrationFeeId,
        registrationDatetime : thealldate                    // 确保 registrationDatetime 正确
      })

    // 判断表单验证是否通过
    if (valid ) {
      if (forms.value.registrationId != null) {
        // 如果 registrationId 存在，执行更新操作
        updateManagement(queryParams.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          getList();
        });
      } else if(restregistration.value > 0) {
        // 否则执行新增操作

        // 查找最近的可用时间
        for (let [key, value] of timeMap) {
          console.log(key, value)
          key = fillToFullTime(key)
          if (key > queryParams.value.registrationTime && value > 0) {
            queryParams.value.registrationTime = key ;
            console.log(queryParams.value.registrationTime)
            addManagemented(queryParams.value).then(response => {
              proxy.$modal.msgSuccess("新增挂号成功");
              getList();
            });
            const [hours, minutes] = queryParams.value.registrationTime.split(':');
            const timeWithoutSeconds = ref(`${hours}:${minutes}`);
            console.log(timeWithoutSeconds.value)
            reduceMount(theid.value,timeWithoutSeconds.value).then(response => {
              console.log(theid.value)
              console.log(response)
            })
            break;
          }
        }

      }else {
        ElMessage({
          message: '当前已无剩余挂号.',
          type: 'warning',
        })
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _registrationIds = row.registrationId || ids.value;
  proxy.$modal.confirm('是否确认删除新增挂号编号为"' + _registrationIds + '"的数据项？').then(function () {
    return delManagement(_registrationIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}



// 获取本地时间（当前日期）
const getLocalDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
function getLocalallDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');  // 月份是从0开始的，需要加1
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  // 返回格式化后的日期字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const thetime = ref('');
const period = ref('');
// 获取当前时间并判断上午或下午
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');

function timereset(){
  const now = new Date();
  const [th, tm, ts] = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`.split(":");
  // 创建新的 Date 对象并设置时间
  const theTime = new Date();
  theTime.setHours(th, tm, ts);
  // 格式化返回时间为 HH:mm:ss
  const hours = String(theTime.getHours()).padStart(2, '0');
  const minutes = String(theTime.getMinutes()).padStart(2, '0');
  const seconds = String(theTime.getSeconds()).padStart(2, '0');

  return `${hours}:${minutes}:${seconds}`;
}
function maketime(hour, minute, second) {
  const now = new Date();
  // 创建一个新的 Date 对象，并设置时、分、秒
  const theTime = new Date(now);
  theTime.setHours(hour, minute, second, 0); // 最后一个参数是毫秒，这里设为0
  // 格式化时间为 "HH:MM:SS"
  return `${String(theTime.getHours()).padStart(2, '0')}:${String(theTime.getMinutes()).padStart(2, '0')}:${String(theTime.getSeconds()).padStart(2, '0')}`;
}

// thetime.value = timereset()
thetime.value = maketime(14, 30, 45)
// 判断当前时间是上午还是下午
period.value = hours < 12 ? '上午' : '下午';

const alldata = ref();

const thedate = getLocalDate()
const thealldate = getLocalallDate()
console.log(thealldate)
forms.value.registrationDate = thedate;

onMounted(() => {
  if (route.query.alldata){
    const data = JSON.parse(route.query.alldata);
    console.log(data)
    alldata.value = data;
    console.log("alldata");
    console.log(alldata.value)
    forms.value.registrationId = alldata.value.registrationId;
    forms.value.patientId = alldata.value.patientId;
    forms.value.employee1 = alldata.value.employee1?.name;
    forms.value.employee2 = alldata.value.employee2?.name;
    forms.value.patientId = alldata.value.patientId;
    forms.value.patient = alldata.value.patient.realName;
    forms.value.patientPhone = alldata.value.patientPhone;
    forms.value.departmentId = alldata.value.departmentId;
    forms.value.registrationDate = alldata.value.registrationDate;
    forms.value.registrationFeeId = alldata.value.registrationFee.id;
    forms.value.membershipCardNumber = alldata.value.patient.membershipCardNumber;
    forms.value.age = alldata.value.patient.age;
    forms.value.phoneNumber = alldata.value.patient.phoneNumber;
    forms.value.gender = alldata.value.patient.gender;
    forms.value.address = alldata.value.patient.address;
    forms.value.idCardNumber = alldata.value.patient.idCardNumber;
    if (alldata.value.patient.receptionStatus === 0){
      forms.value.diagnosisType = '初诊'
    }else {
      forms.value.diagnosisType = '复诊'
    }
  }
});

const scheduleTimeDistribution = ref({
  scheduleTimeId: null,
  upWorkTime1: null,
  upRemainingReservations1: null,
  upWorkTime2: null,
  upRemainingReservations2: null,
  upWorkTime3: null,
  upRemainingReservations3: null,
  upWorkTime4: null,
  upRemainingReservations4: null,
  upWorkTime5: null,
  upRemainingReservations5: null,
  upWorkTime6: null,
  upRemainingReservations6: null,
  doWorkTime1: null,
  doRemainingReservations1: null,
  doWorkTime2: null,
  doRemainingReservations2: null,
  doWorkTime3: null,
  doRemainingReservations3: null,
  doWorkTime4: null,
  doRemainingReservations4: null,
  doWorkTime5: null,
  doRemainingReservations5: null,
  doWorkTime6: null,
  doRemainingReservations6: null,
  doWorkTime7: null,
  doRemainingReservations7: null,
  doWorkTime8: null,
  doRemainingReservations8: null,
  doWorkTime9: null,
  doRemainingReservations9: null
})
const theid = ref();
const timeMap = new Map();
// 选择医生后 以科室 日期 医生 来看剩余预约数
function checkrestcount(employeeId, date) {
  getrestcount(employeeId, date).then(res => {
    console.log("scheduleTimeDistribution");
    scheduleTimeDistribution.value = res.data.doctorSchedule[0].scheduleTimeDistribution;
    console.log(scheduleTimeDistribution.value);
    theid.value = scheduleTimeDistribution.value.scheduleTimeId
    console.log(theid.value)
    restregistration.value = scheduleTimeDistribution.value.upRemainingReservations1 + scheduleTimeDistribution.value.upRemainingReservations2 + scheduleTimeDistribution.value.upRemainingReservations3 + scheduleTimeDistribution.value.upRemainingReservations4 + scheduleTimeDistribution.value.upRemainingReservations5 + scheduleTimeDistribution.value.upRemainingReservations6 + scheduleTimeDistribution.value.doRemainingReservations7 + scheduleTimeDistribution.value.doRemainingReservations8 + scheduleTimeDistribution.value.doRemainingReservations9
    timeMap.set(scheduleTimeDistribution.value.upWorkTime1,scheduleTimeDistribution.value.doRemainingReservations1)
    timeMap.set(scheduleTimeDistribution.value.upWorkTime2,scheduleTimeDistribution.value.doRemainingReservations2)
    timeMap.set(scheduleTimeDistribution.value.upWorkTime3,scheduleTimeDistribution.value.doRemainingReservations3)
    timeMap.set(scheduleTimeDistribution.value.upWorkTime4,scheduleTimeDistribution.value.doRemainingReservations4)
    timeMap.set(scheduleTimeDistribution.value.upWorkTime5,scheduleTimeDistribution.value.doRemainingReservations5)
    timeMap.set(scheduleTimeDistribution.value.upWorkTime6,scheduleTimeDistribution.value.doRemainingReservations6)
    timeMap.set(scheduleTimeDistribution.value.doWorkTime7,scheduleTimeDistribution.value.doRemainingReservations7)
    timeMap.set(scheduleTimeDistribution.value.doWorkTime8,scheduleTimeDistribution.value.doRemainingReservations8)
    timeMap.set(scheduleTimeDistribution.value.doWorkTime9,scheduleTimeDistribution.value.doRemainingReservations9)
    console.log("Total remaining reservations: " + restregistration.value);
    console.log(timeMap)
  })
  }
function fillToFullTime(timeStr) {
  const [hours, minutes] = timeStr.split(":");
  const seconds = "00"; // 默认填充秒为 "00"
  return `${hours}:${minutes}:${seconds}`;
}

getList();
getFeelist();
</script>

<style scoped>
.custom-selector {
  position: relative;
  width: 300px;
  cursor: pointer;
}

.selected-item {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: #f9f9f9;
  text-align: center;
}

.dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  border: 1px solid #ccc;
  background-color: white;
  z-index: 10;
  padding: 5px;
  max-height: 350px; /* 设置最大高度 */
  overflow-y: auto; /* 启用垂直滚动 */
}

.dropdown-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.option-block {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.option-title {
  font-weight: bold;
  color: #333;
}

.option-description {
  font-size: 12px;
  color: #666;
}

.option-block.selected {
  background-color: #409EFF;
  color: white;
}

.option-block:hover {
  background-color: #f0f0f0;
}



</style>
